<script setup lang="ts">
import { computed, h, Reactive, ref , toRef,reactive } from "vue"
import { ElFormItem, ElInput, ElSelect, ElOption, ElTooltip, ElCheckbox, ElButton } from "element-plus";
import CSAdd from "./addCS.vue";
// @ts-ignore
import FullEl from "./full.vue";
import Nifi from "src/nifi";
import {t,tp} from "../../i18n/index"

interface Props {
    modelValue: any
    descriptor: any
    prop:string|string[]
    model: Reactive<any>
    nifi: Nifi
    autofocus?:boolean
    groupId?:string
    refresh:(name:string,sensitive?:boolean) => Promise<any>
}

const  props = withDefaults(defineProps<Props>(),{autofocus:false});
const { modelValue, descriptor, model, nifi,refresh,groupId,prop }  = props;
const autofocus = toRef(props,'autofocus')
const emits = defineEmits<{ 'update:modelValue': [any],delete:[name:string] }>()
//
const temp = reactive({...descriptor})
// @ts-ignore
const { dynamic, displayName,sensitive = false, name, required = false, defaultValue, supportsEl, dependencies = [], description, expressionLanguageScope, allowableValues, identifiesControllerService, identifiesControllerServiceBundle } = temp;
const value = ref(modelValue || defaultValue);
const label = displayName || name;
const show = computed(() => {
    let res = true;
    if(dynamic && value.value === null){return false;}
    if (dependencies.length == 0) return res;
    const v = model.properties || {};
    for (const d of dependencies) {
        const { propertyName, dependentValues = [] } = d;
        const t = v[propertyName]
        if (!t || !dependentValues.includes(t)) {
            res = false;
            break;
        }
    }
    return res;
})
//
const isSelect = allowableValues != undefined;
const isControllerService = identifiesControllerService != undefined;
//
const parameterReg = /^#\{(.*?)\}$/;
const hasParameter = computed(() => nifi.Parameters.enabled.value)
const isParameter = computed(() => {
    // if (!isSelect) return false;
    if (parameterReg.test(value.value)) {
        return true;
    }
    return false;
})
//
const useParameter = ref(isSelect && parameterReg.test(value.value));
const isEmpty = ref(modelValue === '')
const type = ref('')

if (isSelect) {
    if (parameterReg.test(modelValue)) {
        type.value = 'parameter';
    }
    if (isControllerService) {
        type.value = modelValue ? parameterReg.test(modelValue) ? 'parameter' : 'controlService' : 'parameter';
    }
}

//
const parameters = reactive<any[]>([]);
nifi.Parameters.getCurrentParameters().then(res => {
    parameters.push(...res)
})

// const refresh = () => {
//     const url = `/nifi-api/processors/b15252e1-0191-1000-3846-e16cf550a0a7/descriptors?propertyName=${name}&sensitive=${sensitive}`
//     try {
        
//     } catch (error) {
        
//     }
// }

const handleUpdate = () => {
    emits('update:modelValue', value.value === undefined ? null : value.value)
}

const handleUseParameter = (v: any) => {
    // @ts-ignore
    value.value = (v ^ parameterReg.test(value.value || modelValue)) ? '' : value.value || modelValue;
}

// 创建控制器服务
const handleAddControlService = () => {
    nifi.box.dialog((e) => h(CSAdd, { nifi,groupId, type: identifiesControllerService, bundle: identifiesControllerServiceBundle,onFinish:(bool:boolean|string) => {
        if(typeof bool === 'string'){
            refresh(name,sensitive).then((d) => {
                Object.assign(temp,d)
                //
                value.value = bool;
                //
                handleUpdate();
            })
        }
        e.close();
    } }), { showFooter:false })
}

const handleEmpty = (v: any) => {
    value.value = v ? '' : value.value || modelValue;
    isEmpty.value = v;
    handleUpdate();
}
// 删除动态属性
const handleDel = () => {
    value.value = null;
    handleUpdate();
}
//
const handleFull = () => {
    const sv = value.value;
    // const box = nifi.box.dialog(h(ElInput,{modelValue:value.value,"onUpdate:modelValue":(v) => {value.value = v;},autosize:{minRows:10},type:"textarea",class:"min-w-50vw w-full h-full resize"}),{title:label})
    const box = nifi.box.dialog(h(FullEl, { value: sv, onChange: (v) => value.value = v }), { title: label })
    // const box = nifi.box.dialog(h('textarea',{value:value.value,onChange:(v) => {value.value = v;},class:"min-w-50vw min-h-50vh resize"}))
    //
    box.submit(async () => {
        handleUpdate();
    })
    box.cancel(async () => {
        value.value = sv;
    })
}

const handleGoToCS = () => {
    nifi.ControlService.open(groupId,value.value)
}

const handleGoToParameters = () => {
    const name = parameterReg.exec(value.value)?.[1]
    if(name){
        nifi.Parameters.open(name)
    }
    // 
}

const handleTransToParameter = async () => {
    const key = await nifi.Parameters.trans(name,value.value)
    if(key){
        value.value = `#{${key}}`
    }
}


</script>


<template>
    <div v-if="show" class="w-full h-fit p-4px properties-items">
        <ElFormItem :label="label" :prop="prop" :title="label" :required="required" class="flex items-center">
            <template #label>
                <span>{{ tp(label,{defaultValue:label}) }}</span>
                <el-tooltip v-if="description" placement="left" :content="description" popper-class="max-w-20vw">
                    <div class="i-pepicons-pop:question w-1em h-1em c-#aaa"></div>
                </el-tooltip>
            </template>
            <div class="min-w-80px flex gap-4px items-center justify-between">
                <template v-if="isSelect">
                    <el-checkbox v-model="useParameter" :title="t('propertiesitem-useParameter-title')" @change="handleUseParameter"><b>P</b></el-checkbox>
                    <el-button v-if="isControllerService" :disabled="useParameter" :title="t('propertiesitem-addcs-title')"
                        @click="handleAddControlService" type="success" link>
                        <div class="i-majesticons:data-plus-line w-1em h-1em"></div>
                    </el-button>
                </template>
                <template v-else>
                    <el-checkbox v-model="isEmpty" :title="t('propertiesitem-isEmpty-title')" @change="handleEmpty">
                        <div class="i-gg:trash-empty w-1em h-1em c-#E6A23C"></div>
                    </el-checkbox>
                    <b class="c-#67C23A " :title="t('propertiesitem-supportParam-title')">P</b>
                    <b :class="[supportsEl ? 'c-#67C23A' : 'c-gray']"
                        :title="supportsEl ? `${t('propertiesitem-supportsEl-title')} : ${expressionLanguageScope}` : t('propertiesitem-notsupportsEl-title')">EL</b>
                </template>
            </div>
            <template v-if="isSelect">
                <el-select v-if="useParameter" v-model="value" @change="handleUpdate" clearable>
                    <el-option v-for="item in parameters" :key="`${item.name}-${item.value}`" :label="item.name" :value="`#{${item.name}}`"></el-option>
                </el-select>
                <el-select v-else v-model="value" @change="handleUpdate" clearable>
                    <el-option v-for="t in temp.allowableValues" :value="t.allowableValue.value"
                        :label="t.allowableValue.displayName"></el-option>
                </el-select>
            </template>
            <template v-else>
                <el-input v-model="value" @change="handleUpdate" :disabled="isEmpty" :autofocus="autofocus" :show-password="sensitive"  >
                    <template #suffix v-if="!isEmpty">
                        <i class="i-fluent:full-screen-maximize-24-filled w-1em h-1em cursor-pointer"
                            @click="handleFull"></i>
                    </template>
                </el-input>
            </template>
            <!-- 参数跳转 控制器跳转 转换为参数 -->
            <div class="flex items-center min-w-90px">
                <el-button v-if="dynamic" :title="t('propertiesitem-delAttr-title')" type="danger" link @click="handleDel">
                    <div class="i-typcn:delete-outline w-1em h-1em"></div>
                </el-button>
                <el-button v-if="!isParameter && hasParameter" :title="t('propertiesitem-transParam-title')" type="success" link :disabled="!value" @click="handleTransToParameter">
                    <div class="i-tabler:transform w-1em h-1em"></div>
                </el-button>
                <el-button v-if="isParameter" :title="t('propertiesitem-goParam-title')" type="primary" link :disabled="!value" @click="handleGoToParameters" >
                    <div class="i-icon-park-twotone:hand-right w-1em h-1em"></div>
                </el-button>
                <el-button v-if="isControllerService" :title="t('propertiesitem-goCS-title')" type="success" link :disabled="!value" @click="handleGoToCS" >
                    <div class="i-fa6-solid:right-long w-1em h-1em"></div>
                </el-button>
            </div>
        </ElFormItem>
    </div>
</template>


<style>
.properties-items {
    >.el-form-item {
        align-items: center;

        >.el-form-item__label {
            min-width: 10rem;
            max-width: 10rem;
            width: 10rem;
            justify-content: space-between;

            >span {
                flex: 1;
                text-overflow: ellipsis;
                overflow: hidden;
                white-space: nowrap;
            }
        }

        >.el-form-item__label,
        >.el-form-item__content {
            align-items: center;
            flex-wrap: nowrap;
            gap: 1rem;
        }
    }
}

.el-textarea {
    textarea {
        height: 100%;
    }
}

input,
.el-input,
.el-input__wrapper,
.el-select__wrapper,
.el-textarea__inner {
    background: transparent;
}
</style>